package com.adinnet.admin.classs.controller;

import com.adinnet.admin.classCourse.model.ClassCourse;
import com.adinnet.admin.classCourse.service.ClassCourseService;
import com.adinnet.admin.classs.model.Classs;
import com.adinnet.admin.classs.model.vo.ClassCourseReq;
import com.adinnet.admin.classs.model.vo.ClassCreateReq;
import com.adinnet.admin.classs.model.vo.ClassResp;
import com.adinnet.admin.classs.model.vo.ClasssReq;
import com.adinnet.admin.classs.service.ClasssService;
import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.course.service.CourseService;
import com.adinnet.admin.organization.model.Organization;
import com.adinnet.admin.organization.service.OrganizationService;
import com.adinnet.admin.school.model.School;
import com.adinnet.admin.school.service.SchoolService;
import com.adinnet.admin.system.model.SysUser;
import com.adinnet.admin.system.model.vo.SysUserInfo;
import com.adinnet.admin.system.service.SysUserService;
import com.adinnet.admin.teacher.service.TeacherService;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 * 班级名称 前端控制器
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-02
 */
@Controller
@RequestMapping("/classs")
public class ClasssController {

    @Autowired
    private ClasssService classsService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private CourseService courseService;
    @Autowired
    private ClassCourseService classCourseService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TeacherService teacherService;

    @Autowired
    protected HttpServletRequest request;
    
    @RequestMapping()
    public String school(Model model) {

        SysUserInfo sysUserInfo=commonService.getLoginUser();
        // model.addAttribute("organizationList", organizationService.getListByUserRole(sysUserInfo));//机构列表
        // model.addAttribute("schoolList",schoolService.getListByUserRole(sysUserInfo));//校区列表
        // model.addAttribute("courseList",courseService.getListByUserRole(sysUserInfo));//课程列表
        // return "classs/classs.html";

        // 修改原因: 便于前端动态选择/展示 课程 学校 负责人
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.apply("FIND_IN_SET(id , (SELECT GROUP_CONCAT(DISTINCT u.user_id) FROM t_sys_user_role u WHERE u.role_id IN (SELECT r.id FROM t_sys_role r WHERE r.role_code = 'classs') ) )");
        model.addAttribute("sysUserList",JSONObject.toJSON(sysUserService.list(qw)));//班级负责人列表
        model.addAttribute("organizationList", JSONObject.toJSON(organizationService.getListByUserRole(sysUserInfo)));//机构列表
        model.addAttribute("schoolList",JSONObject.toJSON(schoolService.getListByUserRole(sysUserInfo)));//校区列表
        model.addAttribute("courseList",JSONObject.toJSON(courseService.getListByUserRole(sysUserInfo)));//课程列表
        model.addAttribute("maxRoleSerialNumber",sysUserInfo.getMaxRoleSerialNumber());//最大权限
        model.addAttribute("maxRole",sysUserInfo.getMaxRole());//最大权限
        model.addAttribute("teacherList",JSONObject.toJSON(teacherService.getTeacherList()));//教师列表
        return "classs/class.html";
    }

    /**
     * @Description 新增修改班级
     * @author dmm 
     * @param req 班级
     * @param distributionCourse 课程id
     * @createTime: 2020/12/16 18:32
    */
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping("/crudClass")
    public JsonResult crudClass(String distributionCourse,String flag,ClassCreateReq req){
        // 判断班级名称重复
        QueryWrapper<Classs> qw =new QueryWrapper<>();
        qw.eq("class_name",req.getClassName()).eq("deleted",0);
        if( req.getId() != null )qw.ne("id",req.getId());
        if(classsService.count(qw)>0)return JsonResult.error("班级名称重复");
        String[] courseIds = StringUtils.isEmpty(distributionCourse)?null:distributionCourse.split(",");
        List<ClassCourseReq> courseList = new ArrayList<ClassCourseReq>();
        req.setClassCourseReqs(courseList);
        if(null!=courseIds&&courseIds.length>0)for(int i = 0; i< courseIds.length ; i++){
            ClassCourseReq cr = new ClassCourseReq();
            courseList.add(cr);
            cr.setCourseId(Integer.valueOf(courseIds[i]));
            cr.setUnitName("unit"+(i+1));
        }
        if(schoolService.addOrUpdate(req,commonService.getLoginUser(),request))return JsonResult.ok("操作成功");
        return JsonResult.error("操作失败");
    }

    /**
     * @Description 班级课程列表 用于设置课程状态
     * @author dmm 
     * @param id 班级ID
     * @createTime: 2020/12/17 09:29
    */
    @ResponseBody
    @RequestMapping("/getClassCourseList")
    public Object getClassCourseList(String id) {
        return classCourseService.list(new QueryWrapper<ClassCourse>().apply("class_id = {0} AND deleted = 0",id));
    }

    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping("/courseStatus")
    public JsonResult courseStatus(String ids){
        commonService.saveOperation(request,"班级管理-课程状态-申请解锁");
        if(classCourseService.update(new UpdateWrapper<ClassCourse>().set("audit_status",1).apply("FIND_IN_SET(id,{0})",ids)))return JsonResult.ok("操作成功");
        return JsonResult.error("操作失败");
    }
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping("/courseAuditStatus")
    public JsonResult courseAuditStatus(String ids,String status,String auditStatus,String remark){
        commonService.saveOperation(request,"班级管理-课程状态-审核");
        if(classCourseService.update(new UpdateWrapper<ClassCourse>().set("status",status).set("audit_status",auditStatus).set("remark",remark).apply("FIND_IN_SET(id,{0})",ids).apply("audit_status != 0")))return JsonResult.ok("操作成功");
        return JsonResult.error("操作失败：课程未申请解锁");
    }

    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    @RequestMapping("/editClassCourseStatus")
    public JsonResult editClassCourseStatus(ClassCourse entity){
        commonService.saveOperation(request,"班级管理-课程状态-"+(entity.getStatus().intValue()==1?"解锁":"锁定"));
        if(classCourseService.updateById(entity))return JsonResult.ok("操作成功");
        return JsonResult.error("操作失败");
    }



    /**
     * 根据权限查询班级列表
     **/
    @ResponseBody
    @RequestMapping("/list")
    public PageResult<ClassResp> list(ClasssReq classsReq) {
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        return classsService.schoolList(classsReq, sysUserInfo);
    }

    /**
     * 添加班级
     */
    @RequestMapping("/add")
    @ResponseBody
    public JsonResult add(ClassCreateReq classCreateReq) {
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        if (schoolService.addOrUpdate(classCreateReq,sysUserInfo,request)) {
            commonService.saveOperation(request,"新增班级，班级名称："+classCreateReq.getClassName());
            return JsonResult.ok("添加成功");
        }
        return JsonResult.error("添加失败");
    }



    /**
     * 修改班级
     */
    @RequestMapping("/update")
    @ResponseBody
    public JsonResult addOrUpdate(ClassCreateReq classCreateReq) {
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        if (schoolService.addOrUpdate(classCreateReq,sysUserInfo,request)) {
            commonService.saveOperation(request,"修改班级，班级ID："+classCreateReq.getId());
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    /**
     * 删除班级
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Integer classId) {
        commonService.saveOperation(request,"删除班级，班级ID："+classId);
        return classsService.delete(classId);
    }



    /**
     * @description 查询校区下，管辖的班级列表
     * @author chenjia
     * @param
     * @param: schoolId
     * @createTime 2020/12/14 15:38
     */
    @ResponseBody
    @RequestMapping("/getListBySchoolId")
    public List<Classs> getListByOrganizationId(Integer schoolId) {
        SysUserInfo sysUserInfo=commonService.getLoginUser();
        return classsService.getListBySchoolId(schoolId,sysUserInfo);
    }
}
